from Ft.Lib import Uri
from Ft.Xml.Xslt import Transform
from Ft.Xml import CreateInputSource
from brightcontent.util import get_base_url
from wsgixml.applyxslt import setup_xslt_params

BC_NS = 'http://brightcontent.net/ns/'

#temporary until fixed WSGI.xml is out
def setup_xslt_params(ns, params):
    from wsgixml.applyxslt import xsltize
    xsltparams = dict([ ((ns, k), params[k])
                        for k in params
                        if xsltize(params[k]) is not None ])
    return xsltparams


class FeedRenderer(object):
    def __init__(self, application, config):
        self.application = application
        self.config = config

    def start_response(self, status, headers, exc_info=None):
        self.status = status
        self.headers = headers
        self.exc_info = exc_info

    def __call__(self, environ, start_response):
        path = environ.get('PATH_INFO', '')
        cache = environ['beaker.cache'].get_cache('brightcontent')
        try:
            result = cache.get_value(path)
        except:
            result = self.application(environ, self.start_response)
            if environ.get('brightcontent.render', False):
                xslt = environ.get('paste.config')['app_conf']['main_xslt']
                #self.headers = [('Content-type', 'application/xhtml+xml')]
                self.headers = [('Content-type', 'text/html')]
                #expose the environment within XSLT
                params = setup_xslt_params(BC_NS, environ)
                params.update(setup_xslt_params(BC_NS, environ.get('paste.config')['app_conf']))
                #import pprint; pprint.pprint(params)
                weblog_baseuri = get_base_url(environ).decode('utf-8')
                params[(BC_NS, u'weblog-base-uri')] = weblog_baseuri
                # params[(BC_NS, u'static')] = self.config['static'].decode('utf-8')
                #params[(BC_NS, u'static')] = environ.get('paste.config')['app_conf']['static']
                if environ.has_key('paste.recursive.include'):
                    #paste's recursive facilities are available, to
                    #so we can get the XSLT with a middleware call
                    #rather than a full Web invocation
                    xslt_body = environ['paste.recursive.include'](xslt).body
                    xslt = CreateInputSource(xslt_body, Uri.Absolutize(xslt, weblog_baseuri))
                #else just assume the XSLT is a file path or full URL or even string)
                result = Transform(''.join(result[0]), xslt, params=params)
            if isinstance(result, str):
                result = [result]
            cache.set_value(path, result)
        start_response(self.status, self.headers, self.exc_info)
        return result

